# coding:utf-8

import baostock as bs
import pandas as pd
import datetime
from datetime import date
from src.manager.log_manager import LogManager
from src.util.properties_util import PropertiesUtil
from src.manager.oracle_manager import OracleManager
from src.config.oracle_config import OracleConfig

Logger = LogManager.get_logger(__name__)


class CollectStockIndexHandler:
    """
    调用baostock的API获取指数数据的handler
    """

    def __init__(self):
        """
        构造函数，初始化oracle_manager和cursor对象
        """
        super().__init__()
        self.oracle_manager = OracleManager(OracleConfig.Username, OracleConfig.Password, OracleConfig.Url)
        self.oracle_manager.connect()
        self.cursor = self.oracle_manager.get_cursor()

    def insert_stock_index(self):
        """
        根据date，调用baostock的API获取指数数据，并存储到stock_index表中
        """

        # 登录系统
        lg = bs.login()

        Logger.info('获取stock_info表中的所有记录')

        index_begin_date = PropertiesUtil.get_value(
            "\\mywork\\gitcode-repository\\hades\\dev-project\\adam\\src\\main\\resources\\stock-index.properties",
            "stockIndex.time.beginDate")
        index_end_date = PropertiesUtil.get_value(
            "\\mywork\\gitcode-repository\\hades\\dev-project\\adam\\src\\main\\resources\\stock-index.properties",
            "stockIndex.time.endDate")
        Logger.info('采集指数的开始时间为【' + index_begin_date + '】，结束时间为【' + index_end_date + '】')
        index_begin_date = datetime.datetime.strptime(index_begin_date, '%Y%m%d').strftime('%Y-%m-%d')
        index_end_date = datetime.datetime.strptime(index_end_date, '%Y%m%d').strftime('%Y-%m-%d')

        stock_index_list = ['sh.000001', 'sz.399001', 'sz.399005', 'sz.399006']

        if stock_index_list is not None or len(stock_index_list) > 0:
            # 读取并保存股票记录
            for stock_index in stock_index_list:
                rs = bs.query_history_k_data_plus(stock_index,
                                                  "date,code,open,high,low,close,preclose,volume,amount,pctChg",
                                                  start_date=index_begin_date, end_date=index_end_date,
                                                  frequency="d", adjustflag="3")

                # 获取一条记录，将记录合并在一起
                param_list = []
                while (rs.error_code == '0') & rs.next():
                    row_data = rs.get_row_data()
                    param_list.append(
                        (date.fromisoformat(row_data[0]), row_data[1][3:], float(row_data[2]), float(row_data[3]),
                         float(row_data[4]), float(row_data[5]), float(row_data[7]), float(row_data[8]),
                         float(row_data[9]), float(row_data[5]) - float(row_data[6])))
                self.oracle_manager.batch_insert("insert into stock_index(date_, code_, open_price, "
                                                 "highest_price, lowest_price, close_price, volume, "
                                                 "turnover, change_range, change_amount) "
                                                 "values(:1, :2, :3, :4, :5, :6, :7, :8, :9, :10)",
                                                 param_list)

        self.oracle_manager.cursor_close()
        self.oracle_manager.connect_close()

        # 登出系统
        bs.logout()
